
package csc.daonjpa.java.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import csc.daonjpa.java.dao.AccountDAO;
import csc.daonjpa.java.dao.CustomerDAO;
import csc.daonjpa.java.domain.Account;
import csc.daonjpa.java.domain.BaseInfor;
import csc.daonjpa.java.domain.Customer;

/**
 * This controller handles account related actions
 * @author nvu3
 *
 */
@Controller
@RequestMapping(value = "/account")
public class AccountController {
	@Autowired
	private AccountDAO accountDAO;
	
	@Autowired
	private CustomerDAO customerDAO;
	
	@RequestMapping
	public String goAccount(Model model){
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		String loginId = auth.getName();
		List<Account> accounts = accountDAO.getAccounts(loginId);
		model.addAttribute("accounts", accounts);
		return "account";
	}
	
	/**
	 * Adds account to DB
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/createAccount")
	public String addAccount(HttpServletRequest request, Model model) {
		// Read account info from request and save into Account object
		String accountType = request.getParameter("accountType");
		String accountName = request.getParameter("accountName");
		String accountNumber = request.getParameter("accountNumber");
		String availableAmount = request.getParameter("availableAmount");
		
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		String loginId = auth.getName();
		Customer customer = customerDAO.getCustomer(loginId);
		
		Account account = new Account();
		account.setNumber(accountNumber);
		account.setAmount(availableAmount);
		account.setAccountType(accountType);
		account.setAccountName(accountName);
		account.setCustomer(customer);
		
		// Save account to DB
		accountDAO.addAccount(account);
		
		List<Account> accounts = accountDAO.getAccounts(loginId);
		model.addAttribute("accounts", accounts);
		
		return "account";
	}
}
